export class EventBus {
  private eventMap: Record<string, Function[]>;
  private static instance: EventBus;
  constructor() {
    this.eventMap = {};
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new EventBus();
    }
    return this.instance;
  }

  _on(eventName: string, fn: Function) {
    if (!this.eventMap[eventName]) {
      this.eventMap[eventName] = [];
    }
    this.eventMap[eventName].push(fn);
  }

  _emit(eventName: string, ...args: any[]) {
    if (!this.eventMap[eventName]) return;
    this.eventMap[eventName].forEach((fn) => {
      fn(...args);
    });
  }

  _off (eventName: string) {
    this.eventMap[eventName] = [];
  }

  _once (eventName: string, fn: Function) {
    this._on(eventName, (...args: any[]) => {
      fn(...args)
      this._off(eventName)
    })
  }
}

export default EventBus.getInstance()
